package com.gfhd.excel;

import com.csvreader.CsvWriter;
import com.gfhd.excel.util.POIUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Order(1)
@Component
public class Excel2Csv implements ApplicationRunner {

    @Value("${file.putpath}")
    private String putpath;
    @Value("${file.outpath}")
    private String outpath;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        File file = new File(putpath);
        File[] files = file.listFiles(fl -> fl.getName().endsWith(".xls") || fl.getName().endsWith(".CSV") || fl.getName().endsWith(".xlsx"));
        while (true) {
            for (File f : files) {
                String filename = f.getPath();
                FileInputStream fileInputStream = new FileInputStream(f);
                List<String[]> strings = POIUtils.readExcel(filename, fileInputStream);
                String name = f.getName();
                //String ps = filename.substring(0, filename.lastIndexOf("\\")) + "csv\\";
                File psfile = new File(outpath);
                if (!psfile.exists()) psfile.mkdirs();
                String s = outpath + "\\" + name.substring(0, name.lastIndexOf(".")) + ".csv";
                File tempFile = new File(s);
                if (tempFile.exists()) continue;
                CsvWriter csvWriter = new CsvWriter(tempFile.getCanonicalPath(), ',', StandardCharsets.UTF_8);
                for (String[] string : strings) {
                    csvWriter.writeRecord(string);
                }
                csvWriter.close();
            }
            Thread.sleep(30000);
        }
    }
}
